define([], function() {
	/**
	 * datas转map .
	 */
	function toMap(datas) {
		return groupBy(datas, "orgPid");
	}
			
	/**
	 * map转tree(最终需要的) .
	 */
	function toTree(dataMap, pid) {
		var tree = dataMap[pid];
		if(tree == null) {
			return [];
		}
		for(var i = 0; i < tree.length; i++) {
			tree[i].subs = toTree(dataMap, tree[i].orgId);
			tree[i].isSubsShow = true;
		}
		return tree;
	}
			
	/**
	 * 列表处理 .
	 */
	function groupBy(list, key) {
		var map = {};
		for(var i = 0; i < list.length; i++) {
			var item = list[i];
			var subs = map[item[key]];
			if(subs == null) {
				subs = [item];
				map[item[key]] = subs;
			} else {
				subs.push(item);
			}
		}
		return map;
	}
	
	/**
	 * 组织选择树
	 */
	function controller($scope, $modalInstance, $modal, OrgResource, MessageBox) {
		alert("org==========");
		// 获取数据
		$scope.getData = function() {
			// 请求服务：获取树
			OrgResource.getOrgTree().then(function(resp) {
				$scope.datas = resp.data;
				var dataMap = toMap($scope.datas);
				$scope.orgs = toTree(dataMap, 0);
		    });
		};
		
		$scope.getData();
		
		// 展开/收起组织节点
		$scope.openTree = function(org) {
			// 隐藏下级组织
			if (org.isSubsShow) {
				org.isSubsShow = false;
			} else {
				org.isSubsShow = true;
			}
			
		};
		
		
		// 记录选择的组织
		$scope.record = function(org){
			if ($scope.isShown || $scope.isLowerShown || $scope.isEditShown) {
				// 如果已有输入框或编辑框在显示则不做记录
			} else {
				$scope.selectedOrg = org;
			}
		};
		
		// 提交
		$scope.submit = function() {
			if ($scope.selectedOrg) {
				$modalInstance.close($scope.selectedOrg);
			} else {
				MessageBox.confirm("注意","请选择一个组织");
			}
		}
		
		
		// 取消
		$scope.cancel = function() {
			$modalInstance.dismiss('no');
		}
		

	};
	
	return {
		OrgTreeController : ["$scope", "$modalInstance", "$modal", "OrgResource", "MessageBox", controller]
	};
});
